//
//  RecordManager.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/2/8.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import Foundation
import AVFoundation

class RecordManager {

    var recorder: AVAudioRecorder?
    var audioPlayer: AVAudioPlayer?
    
    var player : AVPlayer?
    
    
    var recorTime = 0
    
    //开始录音
    func beginRecord() {
        let session = AVAudioSession.sharedInstance()
        //设置session类型
        do {
            try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        } catch let err{
            print("设置类型失败:\(err.localizedDescription)")
        }
        //设置session动作
        do {
            try session.setActive(true)
        } catch let err {
            print("初始化动作失败:\(err.localizedDescription)")
        }
        //录音设置，注意，后面需要转换成NSNumber，如果不转换，你会发现，无法录制音频文件，我猜测是因为底层还是用OC写的原因
        let recordSetting: [String: Any] = [AVSampleRateKey: NSNumber(value: 44100.0),//采样率
            AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),//音频格式
            AVLinearPCMBitDepthKey: NSNumber(value: 16),//采样位数
            AVNumberOfChannelsKey: NSNumber(value: 2),//通道数
            AVEncoderAudioQualityKey: NSNumber(value: AVAudioQuality.min.rawValue)//录音质量
        ];
        //开始录音
        do {
            let url = URL(fileURLWithPath: file_path!)
            recorder = try AVAudioRecorder(url: url, settings: recordSetting)
            recorder!.prepareToRecord()
            recorder!.record()
            print("开始录音")
        } catch let err {
            print("录音失败:\(err.localizedDescription)")
        }
    }
    
    
    //结束录音
    func stopRecord() {
        if let recorder = self.recorder {
            if recorder.isRecording {
                recorTime = Int(recorder.currentTime)
                print("录音时长：\(recorTime)")
                //wav转mp3
                //开启子线程转换文件
                DispatchQueue.global().async {
                    AudioWrapper.audio_PCMtoMP3(file_path, andDesPath: mp3FilePath)
                    //删除录音文件
                    recorder.deleteRecording()
                    DispatchQueue.main.async {
                        print("正在录音，马上结束它，文件保存到了：\(mp3FilePath!)")
                    }
                }
            }else {
                print("没有录音，但是依然结束它")
            }
            recorder.stop()
            self.recorder = nil
        }else {
            print("没有初始化")
        }
    }
    
    
    //播放
    func play(filePath:String) {
        do {
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(AVAudioSessionCategoryPlayback)
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: filePath))
            print("歌曲长度：\(audioPlayer!.duration)")
            audioPlayer!.play()
        } catch let err {
            print("播放失败:\(err.localizedDescription)")
        }
    }
    
    //播放网络资源
    func playRecoder(filePath:String) {
        
        do{
            let audioSession = AVAudioSession.sharedInstance()
            try audioSession.setCategory(AVAudioSessionCategoryPlayback)
            let songItem = AVPlayerItem(url: URL(string: filePath)!)
            player = AVPlayer(playerItem: songItem)
            player?.replaceCurrentItem(with: songItem)
            player!.play()
        }catch let err {
            print("播放失败:\(err.localizedDescription)")
        }
    }
    
}

